<?php
namespace app\components;

use Yii;
use yii\web\View;
use linslin\yii2\curl;
/**
 * 微信
 */
class WeiXin extends \yii\base\Widget
{
    public $url         = "https://api.weixin.qq.com/cgi-bin/token";
    public $grant_type  = "client_credential"; // authorization_code
    public $appid       = NULL;
    public $secret      = NULL;

    /**
     * init
     */
    public function init()
    {
        if($this->url == NULL){
            $this->url = Yii::$app->params["WEIXIN_URL"];; 
        }
        if($this->grant_type  == NULL){
            $this->grant_type = 'client_credential'; 
        }
        if($this->appid == NULL){
            $this->appid = Yii::$app->params['appId']; 
        }   
        if($this->secret == NULL){
            $this->secret  = Yii::$app->params['appSecret']; 
        }   
    }

    // 获取 access_token 
    public function getToken(){//{{{
        $url = sprintf("%s?grant_type=%s&appid=%s&secret=%s", $this->url, $this->grant_type, $this->appid, $this->secret);

        $curl = new curl\Curl();

        $model = $curl->get($url);

        $conv  = json_decode($model, true);
        
        return $conv['access_token'];
    }//}}}

    // 统一下单支付接口
    public function getUnified(){//{{{
        require_once __DIR__ . "/../components/WxpayAPI_php_v3/lib/WxPay.Api.php";
        require_once __DIR__ . "/../components/WxpayAPI_php_v3/example/WxPay.JsApiPay.php";

        $tools = new \JsApiPay();
        var_dump($tools);
        $openId = $tools->GetOpenid();
        var_dump($openId);exit;
        return $oprnId;
    }//}}}

    // 获取 userId 
    public function getUserId(){//{{{
        //$url = "";

    }//}}}


    // 获取关注者openId
    public function getOpenId($code){
        $url = sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", Yii::$app->params['appId'], Yii::$app->params['appSecret'], $code);

        $curl = new curl\Curl();

        $model = $curl->get($url);

        $conv  = json_decode($model, true);
        
        return $conv;
    }
    

    // 获取签名
    public function getPaySign(){
       
    }

    // get User-Agent
    public function getUserAgent(){
        return Yii::$app->request->getUserAgent();
    }
    

    /**
     * Ends recording a block.
     */
    public function run()
    {
        
    }

}
